#include"snakeLinux.h"

// 初始化用户系统
void initUserSystem() {
    head = NULL;
    currentUser = NULL;
    loadUserScores();
}

// 创建用户节点
UserNode* createUserNode(const char* id) {
    UserNode* newNode = (UserNode*)malloc(sizeof(UserNode));
    if(newNode == NULL) {
        perror("内存分配失败");
        exit(1);
    }
    strcpy(newNode->id, id);
    newNode->score = 0;
    newNode->next = NULL;
    return newNode;
}

// 查找用户
UserNode* findUser(const char* id) {
    UserNode* current = head;
    while(current != NULL) {
        if(strcmp(current->id, id) == 0) {
            return current;
        }
        current = current->next;
    }
    return NULL;
}

// 初始化用户（登录/注册）
void initUser() {
    clearScreen();
    printf("================ Snake Game ================\n");
    printf("请输入你的ID: ");
    char id[50];
    scanf("%s", id);

    currentUser = findUser(id);
    if(currentUser == NULL) {
        currentUser = createUserNode(id);
        currentUser->next = head;  // 插入链表头部
        head = currentUser;
        printf("新用户创建成功: %s\n", id);
    } else {
        printf("欢迎回来 %s，你的最高分数: %d\n", id, currentUser->score);
    }
    printf("按任意键开始游戏...\n");
    getchar();  // 吸收输入ID后的换行符
    getchar();  // 等待用户按键
}

// 更新用户分数（仅保留最高分）
void updateUserScore(int newScore) {
    if(currentUser != NULL) {
        if(newScore > currentUser->score) {
            currentUser->score = newScore;
            printf("恭喜！刷新最高分: %d\n", newScore);
            saveUserScores();  // 保存更新后的分数
        }
    }
}

// 回调函数，用于处理查询结果
static int load_callback(void *NotUsed, int argc, char **argv, char **azColName) {
    UserNode* newNode = (UserNode*)malloc(sizeof(UserNode));
    if (newNode == NULL) {
        perror("内存分配失败");
        exit(1);
    }
    strncpy(newNode->id, argv[0], 49);
    newNode->id[49] = '\0'; 
    newNode->score = atoi(argv[1]);
    newNode->next = head;
    head = newNode;
    return 0;
}

// 保存用户分数到数据库
void saveUserScores() {
    sqlite3 *db;
    char *zErrMsg = 0;
    int rc;
    char sql[512];
    UserNode* current;

    rc = sqlite3_open("user_scores.db", &db);
    if(rc) {
        fprintf(stderr, "无法打开数据库: %s\n", sqlite3_errmsg(db));
        return;
    }

    // 创建表（
    const char* create_table = "CREATE TABLE IF NOT EXISTS users ("
                               "id TEXT PRIMARY KEY,"
                               "score INTEGER);";
    rc = sqlite3_exec(db, create_table, 0, 0, &zErrMsg);
    if(rc != SQLITE_OK) {
        fprintf(stderr, "SQL错误: %s\n", zErrMsg);
        sqlite3_free(zErrMsg);
    }

    // 清空现有数据
    const char* delete_all = "DELETE FROM users;";
    rc = sqlite3_exec(db, delete_all, 0, 0, &zErrMsg);
    if(rc != SQLITE_OK) {
        fprintf(stderr, "SQL错误: %s\n", zErrMsg);
        sqlite3_free(zErrMsg);
    }

    // 插入所有用户数据
    current = head;
    while(current != NULL) {
        snprintf(sql, sizeof(sql), "INSERT INTO users (id, score) VALUES ('%s', %d);", 
                current->id, current->score);
        rc = sqlite3_exec(db, sql, 0, 0, &zErrMsg);
        if(rc != SQLITE_OK) {
            fprintf(stderr, "SQL错误: %s\n", zErrMsg);
            sqlite3_free(zErrMsg);
        }
        current = current->next;
    }
    sqlite3_close(db);
}

// 从数据库加载用户分数
void loadUserScores() {
    sqlite3 *db;
    char *zErrMsg = 0;
    int rc;
    const char* sql = "SELECT id, score FROM users;";

    rc = sqlite3_open("user_scores.db", &db);
    if(rc) {
        fprintf(stderr, "无法打开数据库: %s\n", sqlite3_errmsg(db));
        return;
    }

    while(head != NULL) {
        UserNode* temp = head;
        head = head->next;
        free(temp);
    }

    // 执行查询
    rc = sqlite3_exec(db, sql, load_callback, 0, &zErrMsg);
    if(rc != SQLITE_OK) {
        fprintf(stderr, "SQL错误: %s\n", zErrMsg);
        sqlite3_free(zErrMsg);
    }

    sqlite3_close(db);
}

// 显示分数排行榜（前10名）
void showScoreRanking() {
    clearScreen();
    if(head == NULL) {
        printf("暂无分数记录！\n");
        printf("按任意键返回...\n");
        getchar();
        return;
    }

    // 复制用户链表用于排序（避免修改原链表）
    UserNode* tempHead = NULL;
    UserNode* current = head;
    while(current != NULL) {
        UserNode* newNode = (UserNode*)malloc(sizeof(UserNode));
        if(newNode == NULL) {
            perror("内存分配失败");
            exit(1);
        }
        strcpy(newNode->id, current->id);
        newNode->score = current->score;
        newNode->next = tempHead;
        tempHead = newNode;
        current = current->next;
    }

    // 冒泡排序（从高到低）
    int swapped;
    do {
        swapped = 0;
        UserNode* p = tempHead;
        while(p != NULL && p->next != NULL) {
            if(p->score < p->next->score) {
                // 交换分数
                int tempScore = p->score;
                p->score = p->next->score;
                p->next->score = tempScore;
                // 交换ID
                char tempId[50];
                strcpy(tempId, p->id);
                strcpy(p->id, p->next->id);
                strcpy(p->next->id, tempId);
                swapped = 1;
            }
            p = p->next;
        }
    } while(swapped);

    // 显示排行榜
    printf("====== 分数排行榜 ======\n");
    current = tempHead;
    int rank = 1;
    while(current != NULL && rank <= 10) {
        printf("%d. %-10s 分数: %d\n", rank, current->id, current->score);
        current = current->next;
        rank++;
    }

    // 释放临时链表
    while(tempHead != NULL) {
        UserNode* temp = tempHead;
        tempHead = tempHead->next;
        free(temp);
    }

    printf("\n按任意键返回...\n");
    getchar();  // 吸收前一次输入的换行符
    getchar();  // 等待用户按键
}

// 游戏结束处理
void gameOver() {
    clearScreen();
    printf("====== 游戏结束 ======\n");
    printf("你的最终分数: %d\n", game.score);

    // 更新当前用户分数
    updateUserScore(game.score);

    printf("输入 1 查看排行榜，输入其他键退出: ");
    char key = getchar();
    if(key == '1') {
        showScoreRanking();
    }

    // 清理资源
    clearScreen();
    printf("感谢游玩！\n");
}